package com.cwits.wifi.ui.activity;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cwits.wifi.R;
import com.cwits.wifi.base.BaseActivity2;
import com.cwits.wifi.data.beans.FileInfo;
import com.cwits.wifi.ui.dialog.TwoDialog;
import com.cwits.wifi.ui.view.GalleryAdapter;
import com.cwits.wifi.ui.view.MyImageView;
import com.cwits.wifi.ui.view.PicGallery;
import com.cwits.wifi.util.AppUtil;
import com.cwits.wifi.util.IConstant;
import com.cwits.wifi.util.Util;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.constant.WBConstants;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

public class PhotoActivity extends BaseActivity2 implements View.OnClickListener, IConstant, IWeiboHandler.Response {
    private static final int THUMB_SIZE = 150;
    private String defaultPath;
    private List<FileInfo> allDataInfoList = null;
    private String mPhotoFile;
    private Button mBtnCancle;
    private LinearLayout mLlShare, mLlWx, mLlWb, mLlPyq, mLlOther;
    private ImageView mImBack;
    private TextView mTvTime;
    private PicGallery mGallery;
    private RelativeLayout mRlShare, mRlDel, mRlTop;
    private TwoDialog twoDialog;
    private IWXAPI api;
    public static int WXSceneSession = 0;
    public static int WXSceneTimeline = 1;
    private int mPosition = 0;
    // 屏幕宽度
    public static int screenWidth;
    // 屏幕高度
    public static int screenHeight;
    private GalleryAdapter mAdapter;
    private boolean isInstalledWeibo;

    /**
     * 微博分享的接口实例
     */
    private IWeiboShareAPI mWeiboShareAPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            super.setTranslucen(R.color.transparent);
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

            //mHandler.sendEmptyMessageDelayed(HIDE_VIDEOCONTROL, 3000);

            setContentView(R.layout.activity_photo_land);
        } else {
            setContentView(R.layout.activity_photo);
        }
        init();
        initialize();
        initView();

    }

    private void initialize() {
        // 创建微博 SDK 接口实例
        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this, APP_KEY);

        // 获取微博客户端相关信息，如是否安装、支持 SDK 的版本
        isInstalledWeibo = mWeiboShareAPI.isWeiboAppInstalled();
        int supportApiLevel = mWeiboShareAPI.getWeiboAppSupportAPI();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 从当前应用唤起微博并进行分享后，返回到当前应用时，需要在此处调用该函数
        // 来接收微博客户端返回的数据；执行成功，返回 true，并调用
        // {@link IWeiboHandler.Response#onResponse}；失败返回 false，不调用上述回调
        mWeiboShareAPI.handleWeiboResponse(intent, this);
    }

    private void initView() {
        WindowManager wm = (WindowManager) getApplication()
                .getSystemService(Context.WINDOW_SERVICE);

        screenWidth = wm.getDefaultDisplay().getWidth();
        screenHeight = wm.getDefaultDisplay().getHeight() - dip2px(this, 94);

        //System.out.print(width + "----" + height);

        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(

                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

        params.height = screenWidth * 3 / 4;

        params.width = screenWidth;

        //mSurfaceView.setWidthAndHeight(width,width*9/16);
        //mImPhoto.setLayoutParams(params);
    }

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo = mConnectivityManager.getActiveNetworkInfo();
                if (netInfo != null && netInfo.isAvailable() && netInfo.isConnected()
                        && netInfo.getState().equals(NetworkInfo.State.CONNECTED)) {
                    ///////网络连接
                    //showToastLong("网络连接");

                } else {
                    ////////网络断开
                    // showToastLong("网络断开");
                }
            }
        }
    };


    private void init() {
        api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        api.registerApp(APP_ID);

        mGallery = (PicGallery) findViewById(R.id.photo_activity_gl_photo);
        mGallery.setOnCancleShareListener(new PicGallery.OnCancleShareListener() {
            @Override
            public void onCancleShare() {
                if (mLlShare.getVisibility() == View.VISIBLE)
                    mLlShare.setVisibility(View.GONE);
            }
        });
        mGallery.setVerticalFadingEdgeEnabled(false);// 取消竖直渐变边框
        mGallery.setHorizontalFadingEdgeEnabled(false);// 取消水平渐变边框
        mGallery.setDetector(new GestureDetector(this,
                new MySimpleGesture()));
        mAdapter = new GalleryAdapter(this);
        mGallery.setAdapter(mAdapter);
        mGallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    if (null != allDataInfoList && allDataInfoList.size() != 0)
                        mTvTime.setText(allDataInfoList.get(mPosition).getCreateDate());
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);
        Intent intent = getIntent();
        mPosition = Integer.valueOf(intent.getStringExtra("photo_file"));
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            mImBack = (ImageView) findViewById(R.id.photo_activity_im_back);
            mImBack.setOnClickListener(this);

        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTvTime = (TextView) findViewById(R.id.photo_activity_tv_time);

            mRlTop = (RelativeLayout) findViewById(R.id.photo_activity_rl_top);

        }
        mBtnCancle = (Button) findViewById(R.id.photo_activity_btn_cancle);
        mLlShare = (LinearLayout) findViewById(R.id.photo_activity_ll_share);
        mLlWx = (LinearLayout) findViewById(R.id.photo_activity_ll_share_wx);
        mLlWb = (LinearLayout) findViewById(R.id.photo_activity_ll_share_wb);
        mLlPyq = (LinearLayout) findViewById(R.id.photo_activity_ll_share_wx_pyq);
        mRlDel = (RelativeLayout) findViewById(R.id.photo_activity_rl_left);
        mRlShare = (RelativeLayout) findViewById(R.id.photo_activity_rl_right);
        mLlOther = (LinearLayout) findViewById(R.id.photo_activity_ll_share_other);
        //mBitmap = getLoacalBitmap(mPhotoFile); //从本地取图片(在cdcard中获取)  //
        //if (mBitmap != null)
        // mImPhoto.setImageBitmap(mBitmap); //设置Bitmap

        mLlOther.setOnClickListener(this);
        mBtnCancle.setOnClickListener(this);
        mRlDel.setOnClickListener(this);
        mRlShare.setOnClickListener(this);
        mLlWx.setOnClickListener(this);
        mLlWb.setOnClickListener(this);
        mLlPyq.setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();

        new Thread(new Runnable() {
            @Override
            public void run() {

                defaultPath = Environment.getExternalStorageDirectory().getPath() + "/lipeibao/168cardev/photo";
                if (allDataInfoList != null) {
                    allDataInfoList.clear();
                }
                allDataInfoList = AppUtil.getLocalFileInfo(defaultPath);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mAdapter.setData(allDataInfoList);
                        mAdapter.notifyDataSetChanged();
                        mGallery.setSelection(mPosition);
                    }
                });

            }
        }).start();
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            if (null != allDataInfoList && allDataInfoList.size() != 0)
                mTvTime.setText(allDataInfoList.get(mPosition).getCreateDate());
        }
    }

    /**
     * 接收微客户端博请求的数据。
     * 当微博客户端唤起当前应用并进行分享时，该方法被调用。
     */
    @Override
    public void onResponse(BaseResponse baseResponse) {
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, R.string.weibosdk_demo_toast_share_success, Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, R.string.weibosdk_demo_toast_share_canceled, Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(this,
                        getString(R.string.weibosdk_demo_toast_share_failed) + "Error Message: " + baseResponse.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }
    }


    private class MySimpleGesture extends GestureDetector.SimpleOnGestureListener {
        // 按两下的第二下Touch down时触发
        public boolean onDoubleTap(MotionEvent e) {

            View view = mGallery.getSelectedView();
            if (view instanceof MyImageView) {
                MyImageView imageView = (MyImageView) view;
                if (imageView.getScale() > imageView.getMiniZoom()) {
                    imageView.zoomTo(imageView.getMiniZoom());
                } else {
                    imageView.zoomTo(imageView.getMaxZoom());
                }

            } else {

            }
            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            // Logger.LOG("onSingleTapConfirmed",
            // "onSingleTapConfirmed excute");
            // mTweetShow = !mTweetShow;
            // tweetLayout.setVisibility(mTweetShow ? View.VISIBLE
            // : View.INVISIBLE);
            return true;
        }
    }

    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void deleteFile() {
        File dirFile = new File(mPhotoFile);
        if (!dirFile.exists()) {
            return;
        }
        if (dirFile.isDirectory()) {
            String[] children = dirFile.list();
            for (int i = 0; i < children.length; i++) {
                new File(dirFile, children[i]).delete();
            }
        }

        dirFile.delete();
    }

    private void getPhotoPath() {
        mPosition = mGallery.getSelectedItemPosition();
        mPhotoFile = allDataInfoList.get(mPosition).getPath();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.photo_activity_im_back:
                if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                } else {
                    finish();
                }
                break;
            case R.id.photo_activity_rl_left:
                getPhotoPath();
                //showTwoDialog();
                showDeleFile();
                break;
            case R.id.photo_activity_rl_right:
                if (mApplication.getIsOffLineMode() == false) {
                    disconnectDevice();
                    mApplication.setIsOffLineMode(true);
                    mApplication.setRealCamera(false);
                    mApplication.setIsNeedReconnect(true);
                }
                mLlShare.setVisibility(View.VISIBLE);
                mGallery.setOpenShare(true);
                break;
            case R.id.photo_activity_btn_cancle:
                mGallery.setOpenShare(false);
                mLlShare.setVisibility(View.GONE);
                break;
            /** 分享到微信好友 */
            case R.id.photo_activity_ll_share_wx:
                shareWX(WXSceneSession);
                break;
            /** 分享到朋友圈 */
            case R.id.photo_activity_ll_share_wx_pyq:
                shareWX(WXSceneTimeline);
                break;
            /** 分享到微博 */
            case R.id.photo_activity_ll_share_wb:
                if (mWeiboShareAPI.checkEnvironment(true)) {
                    // 注册第三方应用 到微博客户端中，注册成功后该应用将显示在微博的应用列表中。
                    mWeiboShareAPI.registerApp();
                    shareWB();
                }
                break;
            case R.id.photo_activity_ll_share_other:
                getPhotoPath();
                Intent shareIntent1 = new Intent();
                shareIntent1.setAction(Intent.ACTION_SEND);
                shareIntent1.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(mPhotoFile)));
                shareIntent1.setType("image/*");
                startActivity(Intent.createChooser(shareIntent1, "分享到"));
                break;
        }

    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    /**
     * 微博分享给好友
     */
    private void shareWB() {
        if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
            getPhotoPath();
            int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
            if (supportApi >= 10351 /*ApiUtils.BUILD_INT_VER_2_2*/) {
                //高版本 可分享多种
                sendMultiMessage();
            } else {
                //低版本 只能分享一种
                sendSingleMessage();
            }
        } else {
            Toast.makeText(this, R.string.weibosdk_demo_not_support_api_hint, Toast.LENGTH_SHORT).show();
        }
    }

    private void sendMultiMessage() {
        // 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.imageObject = getImageObj();
        //weiboMessage.textObject = getTextObj();
        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        mWeiboShareAPI.sendRequest(request);
    }

    private void sendSingleMessage() {
        // 1. 初始化微博的分享消息
        // 用户可以分享文本、图片、网页、音乐、视频中的一种
        WeiboMessage weiboMessage = new WeiboMessage();
        weiboMessage.mediaObject = getImageObj();
        // weiboMessage.mediaObject = getTextObj();
        // 2. 初始化从第三方到微博的消息请求
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.message = weiboMessage;

        // 3. 发送请求消息到微博，唤起微博分享界面
        mWeiboShareAPI.sendRequest(request);
    }

    /**
     * 创建图片消息对象。
     *
     * @return 图片消息对象。
     */
    private ImageObject getImageObj() {
        ImageObject imageObject = new ImageObject();
        BitmapDrawable bitmapDrawable = new BitmapDrawable(getLoacalBitmap(mPhotoFile));
        imageObject.setImageObject(bitmapDrawable.getBitmap());
        return imageObject;
    }

    /**
     * 创建文本消息对象。
     *
     * @return 文本消息对象。
     */
    private TextObject getTextObj() {
        TextObject textObject = new TextObject();
        textObject.text = "ceshiceshiceshi";
        return textObject;
    }

    /**
     * 微信分享给好友
     */
    private void shareWX(int Scene) {

        getPhotoPath();

        WXImageObject imgObj = new WXImageObject();
        imgObj.setImagePath(mPhotoFile);

        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imgObj;

        Bitmap bmp = BitmapFactory
                .decodeFile(mPhotoFile);
        Bitmap thumbBmp = Bitmap
                .createScaledBitmap(bmp,
                        THUMB_SIZE,
                        THUMB_SIZE, true);
        //Toast.makeText(this,"size="+getBitmapSize(bmp),Toast.LENGTH_LONG).show();
        bmp.recycle();
        if (thumbBmp != null) {
            msg.thumbData = Util.bmpByteArray(thumbBmp,
                    true);
            //msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("img");
            req.message = msg;
            req.scene = Scene;
            api.sendReq(req);
        } else {
            Toast.makeText(this, getString(R.string.no_error_share), Toast.LENGTH_LONG).show();
        }


    }

    private void showDeleFile() {
        twoDialog = new TwoDialog(PhotoActivity.this, getString(R.string.dialog_tip), getString(R.string.photo_del_pho), deleFileListener);
        twoDialog.show();
    }

    private View.OnClickListener deleFileListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.dialog_btn2_rl_ok:

                    twoDialog.dismiss();
                    deleteFile();
                    if (mPosition == allDataInfoList.size()) {
                        mPosition = mPosition - 1;
                    } else if (mPosition == 0 && allDataInfoList.size() == 1) {
                        finish();
                    }
                    for (int i = 0; i < allDataInfoList.size(); i++) {
                        if (allDataInfoList.get(i).getPath().equals(mPhotoFile)) {
                            allDataInfoList.remove(i);
                        }
                    }
                    mAdapter.setData(allDataInfoList);
                    mAdapter.notifyDataSetChanged();
                    mGallery.setSelection(mPosition);
                    //finish();

                    break;
                case R.id.dialog_btn2_rl_canale:
                    twoDialog.dismiss();
                    break;
            }
        }
    };

    private void showTwoDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(PhotoActivity.this);
        // final Dialog builder = new Dialog(getApplicationContext());
        View view = View.inflate(PhotoActivity.this, R.layout.dialog_btn2,
                null);
        TextView tvInfo = (TextView) view.findViewById(R.id.dialog_btn2_tv_info);
        RelativeLayout rlClose = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_canale);
        RelativeLayout rlOk = (RelativeLayout) view.findViewById(R.id.dialog_btn2_rl_ok);

        tvInfo.setText(getString(R.string.photo_del_pho));
        builder.setView(view);
        builder.setCancelable(false);
        final AlertDialog dialog = builder.create();
        rlOk.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                deleteFile();
                finish();
            }
        });

        rlClose.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setView(view, 0, 0, 0, 0);
        dialog.show();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mReceiver);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

}
